package com.redistest.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.redistest.seckill.mapper.UserMapper;
import com.redistest.seckill.pojo.User;
import com.redistest.seckill.service.IUserService;
import com.redistest.seckill.utils.PasswordUtils;
import com.redistest.seckill.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;


@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private IUserService IUserService;

    @PostMapping("/register")
    public Result register(@Valid @RequestBody User user) {
        // 检查用户是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickname, user.getNickname());
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            return Result.error(400, null, "用户已存在");
        }
        // 密码加密
        String p1 = user.getPassword();
        String p = PasswordUtils.hashPassword(p1);
        user.setPassword(p);
        Date date = new Date();
        user.setRegisterDate(date);
        user.setLastLoginDate(date);
        user.setLoginCount(1);
        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            // 捕获唯一键冲突异常（需数据库有唯一约束）
            return Result.error(400, null, "用户名已被占用");
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error(500, null, "系统错误");
        }
        return Result.success(null,"注册成功");
    }

    @PostMapping("/doLogin")
    public Result doLogin( @RequestBody User user ) {
        System.err.println(user.getNickname());
        System.err.println(user.getPassword());
        return IUserService.Login(user.getNickname(), user.getPassword());
    }

}
